package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.MessageConstant;
import com.ruan.common.Result;
import com.ruan.exception.BusinessException;
import com.ruan.mapper.AdminMapper;
import com.ruan.mapper.CommonUserMapper;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.PositionMapper;
import com.ruan.pojo.Admin;
import com.ruan.pojo.CommonUser;
import com.ruan.pojo.Employee;
import com.ruan.pojo.Position;
import com.ruan.pojoExt.CommonUserExt;
import com.ruan.service.CommonUserService;
import com.ruan.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.util.Random;

@Service
@Slf4j
@Transactional
public class CommonUserServiceImpl extends ServiceImpl<CommonUserMapper, CommonUser> implements CommonUserService {

    @Resource
    private CommonUserMapper commonUserMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeService employeeService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private BCryptPasswordEncoder encoder;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private AdminMapper adminMapper;


    //员工注册账号
    @Override
    public Result register(CommonUser commonUser) {
//        System.out.println("员工register传的值是："+commonUser);
        if (commonUser!=null){
//            String phone = commonUser.getPhone();
//            String code = commonUser.getCode();
//            ValueOperations ops = redisTemplate.opsForValue();
//            String codeInRedis = String.valueOf(ops.get(phone));

//            System.out.println("code是："+code);
//            System.out.println("codeInRedis是："+codeInRedis);

//            if (codeInRedis == null){
//                return new Result(Code.CODE_EXPIRED,"验证码已过期，请重新获取！");
//            }

//            if (!code.equals(codeInRedis)){
//                return new Result(Code.CODE_ERR,"验证码错误！");
//            }

            //BCryptPasswordEncoder是Spring Security提供的一个用于密码加密和验证的类。
            // 使用BCrypt算法来对密码进行哈希加密，是一种安全可靠的加密算法，常用于存储用户密码或敏感信息
//            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//            String encodedPassword = encoder.encode(需要加密的密码);

            String username = commonUser.getUsername();
//            //如果用户名里有admin字符，则去掉???
            if (username.contains("adminRole")){
                return new Result(Code.REGISTER_ERR,"该用户名已存在！");
            }
            String passwordEncode = encoder.encode(commonUser.getPassword());
            //System.out.println("passwordEncode加密成功了没"+passwordEncode);
            LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommonUser::getUsername,username);
            int count = commonUserMapper.selectCount(queryWrapper);
            if (count > 0){
                return new Result(Code.REGISTER_ERR,"该用户名已被占用！");
            }
            LambdaQueryWrapper<CommonUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(CommonUser::getPhone,commonUser.getPhone());
            int count1 = commonUserMapper.selectCount(queryWrapper1);
            if (count1 > 0){
                return new Result(Code.REGISTER_ERR,"该手机号已注册！");
            }
            commonUser.setStatus("正常");
            commonUser.setPassword(passwordEncode);
//            commonUser.setPhone(commonUser.getPhone());
            commonUserMapper.insert(commonUser);
            //注册成功后删除redis中的验证码
//            redisTemplate.delete(phone);
            return new Result(Code.REGISTER_OK,"注册成功");
        }else {
            return new Result(Code.REGISTER_ERR,"请填写完整的注册信息！");
        }
    }


    //普通员工登录
    @Override
    public Result employeeLogin(CommonUser commonUser) {
        //1、将页面提交的密码进行MD5加密处理
        String password=commonUser.getPassword();
//        password= DigestUtils.md5DigestAsHex(password.getBytes()).trim();

        //2、根据页面提交的用户名查询管理员数据库
        LambdaQueryWrapper<CommonUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getUsername,commonUser.getUsername());
        CommonUser commonUserQuery = commonUserMapper.selectOne(queryWrapper);


        //3、如果没有查询到则返回登录失败结果
        if (commonUserQuery == null){
            return new Result(Code.LOGIN_ERR, MessageConstant.LOGIN_ERR_PASS);
        }
        //4、密码对比，如果不一致返回登录失败结果
        if (!password.equals(commonUserQuery.getPassword())){
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_PASS);
        }

        //5、如果账号状态为”禁用“，则返回登录失败
        if (commonUserQuery.getStatus().equals("禁用")){
            return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_STATUS);
        }
        String phone = commonUserQuery.getPhone();
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getPhone,phone);
        int count = employeeMapper.selectCount(lambdaQueryWrapper);
        Employee employee = null;
        if(count == 1) {
            employee = employeeMapper.selectOne(lambdaQueryWrapper);
        }else if(count > 1){
            return new Result(Code.LOGIN_ERR,"该手机号已注册多个员工，请联系管理员");
        }else{
            return new Result(Code.LOGIN_ERR,"找不到员工信息");
        }
        //6、入职登记待审核中，返回登录失败
        if (employee!=null){
            if (employee.getStatus().equals("待审核")){
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                //System.out.println("获取到request.getSession().getAttribute了吗"+request.getSession().getAttribute("employee"));
                request.getSession().removeAttribute("employee");//尝试登录失败，清空重复登录验证session
                //System.out.println("清除掉request.getSession().getAttribute了吗"+request.getSession().getAttribute("employee"));
                return new Result(Code.LOGIN_ERR,MessageConstant.LOGIN_ERR_AUDIT);
            }
        }

        return new Result(Code.LOGIN_OK,commonUser, MessageConstant.LOGIN_OK);
    }


   //通过手机号查询员工表中的员工
    @Override
    public Result selectByPhone(String phone) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper);

        if (employee!=null && !employee.getStatus().equals("待审核")){
            //判断employee对象的状态不等于"待审核"
            return new Result(Code.SELECT_OK,true);
        }else {
            return new Result(Code.SELECT_ERR,"请先填写入职申请！");
        }
    }


   //员工入职前信息填写提交
    @Override
    public void addUser(Employee employee, HttpServletRequest request) {

        String phone = employee.getPhone();
        String email = employee.getEmail();

        LambdaQueryWrapper<Employee> queryWrapperEmail = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Employee> queryWrapperPhone = new LambdaQueryWrapper<>();

        queryWrapperPhone.eq(Employee::getPhone,phone);
        queryWrapperEmail.eq(Employee::getEmail,email);

        int employeeQueryByPhone = employeeMapper.selectCount(queryWrapperPhone);
        int employeeQueryByEmail = employeeMapper.selectCount(queryWrapperEmail);

        if (employeeQueryByPhone > 0){
            throw new BusinessException(Code.SAVE_ERR,"该手机号已注册！");
        }

        if (employeeQueryByEmail > 0){
            throw new BusinessException(Code.SAVE_ERR,"该邮箱已注册！");
        }

        employee.setStatus("正式");//待审核
        LambdaQueryWrapper<Position> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Position::getPname,"员工");
        if(positionMapper.selectCount(queryWrapper)==0){
            throw new BusinessException(Code.SAVE_ERR,"请先添加普通员工职位！");
        }else if(positionMapper.selectCount(queryWrapper) > 1){
            throw new BusinessException(Code.SAVE_ERR,"该职位存在多个，请联系管理员！");
        }
        Position position = positionMapper.selectOne(queryWrapper);
        if(position!=null){
            employee.setPositionId(position.getId());//默认是普通员工
        }
        //随机给一个6位数的工号
        employee.setJobId(String.valueOf(new Random().nextInt(900000)+100000));
        employee.setStatus("正式");
        employee.setWorktime(new Date(System.currentTimeMillis()));
        //入职之后才有机会升值
        //由于不是通过验证码注册(本在这里存手机号)，所以需要在这里给该员工的账号存入手机号,本来就是根据手机号找到该员工对应的账号的。。。。
//        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CommonUser::getPhone,phone);
//        CommonUser commonUser =
        Integer a = employeeMapper.insert(employee);
//        System.out.println("入职信息填写成功了吗："+a);
        if(a!=null){
            request.getSession().removeAttribute("employee");//退出登录
//            System.out.println("普通员工的Session清空了？");
//            System.out.println("退出登录成功了吗");
        }
    }


    //注册时判断员工账号是否已存在
    @Override
    public CommonUser selectOneByPhone(String phone) {
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getPhone,phone);
        CommonUser commonUser = commonUserMapper.selectOne(queryWrapper);
        CommonUser result = commonUser != null ? commonUser : new CommonUser();
        return result;
    }


    //定时任务判断该员工账号是否可用
    @Override
    public Result judgeStatus(Integer userId) {
        CommonUser commonUser = commonUserMapper.selectById(userId);
//        System.out.println("当前用户登陆的用户是："+commonUser);
        if (commonUser!=null){
            String status = commonUser.getStatus();
            if(status.equals("禁用")){
                return new Result(Code.USER_RESIGN,"您已离职，账号无法使用！");
            }else {
                return new Result(Code.SELECT_OK,"账号状态良好!");
            }
        }else {
            return new Result(Code.SELECT_ERR,"账号已删除！");
        }
    }


    //根据用户名查找用户
    @Override
    public Result selectUsername(String username) {
        LambdaQueryWrapper<CommonUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommonUser::getUsername,username);
        int count = commonUserMapper.selectCount(queryWrapper);
        if (count > 0){
            return new Result(Code.USER_EXISTS,"该用户名已存在！");
        }
        return new Result(Code.USER_NOT_EXISTS,"该用户名不存在！");
    }

    //根据用户名查找管理员
    @Override
    public Result selectAdminUsername(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username+"adminRole");
        Integer count = adminMapper.selectCount(queryWrapper);
        if (count > 0){
            return new Result(Code.USER_EXISTS,"该名称已存在！");
        }else{
            return new Result(Code.USER_NOT_EXISTS,"该名称不存在！");
        }
    }
}
